#include "typedelegate.h"
#include <QtGui/QComboBox>

const int NTYPES = 16;

QStandardItemModel TypeDelegate::model(NTYPES,1);

TypeDelegate::TypeDelegate(QObject *parent)
	: QItemDelegate(parent)
{
	static bool isInit = false;
	if (isInit) 
		return;

	QModelIndex index;
	QVariant::Type type;
	for (int row=0; row<NTYPES; ++row) {
		index = model.index(row, 0, QModelIndex());
		type = static_cast<QVariant::Type>(row +1);
		model.setData(index, QVariant(QByteArray(QVariant::typeToName(type))));
		model.setData(index, QVariant(row+1), Qt::UserRole);
	}
}

TypeDelegate::~TypeDelegate()
{

}

QWidget * TypeDelegate::createEditor ( QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
	QComboBox *editor = new QComboBox(parent);
	editor->setModel(&model);

	return editor;
}

void TypeDelegate::setEditorData ( QWidget * editor, const QModelIndex & index ) const
{
	QByteArray value = index.data().toByteArray();
	QVariant::Type type = QVariant::nameToType(value.constData());
	int boxIndex = type - 1;

	QComboBox *box = static_cast<QComboBox*>(editor);
	box->setCurrentIndex(boxIndex);
}

void TypeDelegate::setModelData ( QWidget * editor, QAbstractItemModel * model, const QModelIndex & index ) const
{
	QComboBox *box = static_cast<QComboBox*>(editor);

	model->setData(index, box->itemData(box->currentIndex()));
}
